<script setup lang="ts" name="JxtechUnitDialogExt">
import { reactive, ref, Ref, watch, nextTick, computed } from "vue";
import { JxtechUnitDialog } from "@whjxtech/jxtech-component";
import { orgUnitTree } from "@/api/modules/org/tree";

interface JxtechUnitDialogExtProps {
  /**已选部门id */
  selectUnitIds?: string;
  /**已选部门text */
  selectUnitTexts?: string;
  /**选择模式 单选or多选 */
  multiple?: boolean;
  /**自定义属性key label children isLeaf */
  treeProps?: any;
  /**默认展开的key */
  defaultExpandedKeys?: string[];
  /**dialog对话框是否显示 */
  visible?: boolean;
  appendToBody?: boolean;
}

const emit = defineEmits<{
  (e: "update:visible", val: boolean): void;
  /**id双向绑定 */
  (e: "update:selectUnitIds", val: string): void;
  /**text双向绑定 */
  (e: "update:selectUnitTexts", val: string): void;
  /**点击确认触发事件 */
  (e: "finish", ids: string, texts: string): void;
  /**点击取消触发事件 */
  (e: "cancel"): void;
}>();

const props = withDefaults(defineProps<JxtechUnitDialogExtProps>(), {
  selectUnitIds: "",
  selectUnitTexts: "",
  multiple: false,
  treeProps: () => ({
    id: "id",
    label: "text",
    children: "children",
    isLeaf: "leaf"
  }),
  defaultExpandedKeys: () => ["10000"],
  visible: false,
  appendToBody: true
});

const visibleModelValue = ref(props.visible);
watch(
  () => props.visible,
  value => {
    visibleModelValue.value = value;
  }
);
watch(visibleModelValue, value => {
  emit("update:visible", value);
  if (value) {
    // nextTick(() => {});
  }
});
const selectUnitIdsModelValue = ref(props.selectUnitIds);
watch(
  () => props.selectUnitIds,
  value => {
    selectUnitIdsModelValue.value = value;
  }
);
watch(selectUnitIdsModelValue, value => {
  emit("update:selectUnitIds", value);
});
const selectUnitTextsModelValue = ref(props.selectUnitTexts);
watch(
  () => props.selectUnitTexts,
  value => {
    selectUnitTextsModelValue.value = value;
  }
);
watch(selectUnitTextsModelValue, value => {
  emit("update:selectUnitTexts", value);
});

const JxtechUnitDialogExtState = reactive({
  loadData: (queryParams: { id: string }) => orgUnitTree(queryParams),
  onFinish: (ids: string, texts: string) => {
    emit("finish", ids, texts);
  },
  onCancel: () => emit("cancel")
});
</script>

<template>
  <jxtech-unit-dialog
    v-model:visible="visibleModelValue"
    :load-data="JxtechUnitDialogExtState.loadData"
    v-model:select-unit-ids="selectUnitIdsModelValue"
    v-model:select-unit-texts="selectUnitTextsModelValue"
    :multiple="multiple"
    :tree-props="treeProps"
    :default-expanded-keys="defaultExpandedKeys"
    @finish="JxtechUnitDialogExtState.onFinish"
    @cancel="JxtechUnitDialogExtState.onCancel"
    :append-to-body="appendToBody"
  ></jxtech-unit-dialog>
</template>

<style lang="scss" scoped></style>
